/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package testAgent.behaviours.responder;

import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.DataStore;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.FailureException;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.RefuseException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.proto.AchieveREResponder;

import java.io.IOException;

import tp3.gui.EquationProducer;
import udes.ds.agent.Equation;

/**
 * @author Cody Stoutenburg
 * 
 */
public abstract class EquationSolverResponderBehaviours extends
		AchieveREResponder {
	private static final long serialVersionUID = -6911675989931972544L;

	public static final String IS_CALCUL_FINISH = "EquationSolverResponderBehaviours: finish";
	protected static final String RESULT = "EquationSolverResponderBehaviours: result";

	private Equation equationToSolve;

	/**
	 * @param a
	 * @param mt
	 */
	public EquationSolverResponderBehaviours(Agent a, MessageTemplate mt) {
		super(a, mt);
	}

	@Override
	protected ACLMessage handleRequest(ACLMessage request)
			throws NotUnderstoodException, RefuseException {
		try {
			DFService.deregister(myAgent);
		} catch (FIPAException e) {
			e.printStackTrace();
		}

		// register here not in constructor because here we are call each time
		// handle request is call but not in the constructor
		WaitUntilSolve solve = new WaitUntilSolve();
		solve.setDataStore(getDataStore());
		registerPrepareResultNotification(solve);

		ACLMessage msg = null;
		try {
			equationToSolve = (Equation) request.getContentObject();
			msg = solveEquation(request, equationToSolve);
		} catch (UnreadableException e1) {
			e1.printStackTrace();
		}

		return msg;
	}

	protected abstract ACLMessage solveEquation(ACLMessage request,
			Equation equationToSolve);

	private class WaitUntilSolve extends Behaviour {
		private static final long serialVersionUID = -3258116832158220666L;

		private boolean isFinish;

		public WaitUntilSolve() {
			super();
			isFinish = false;
		}

		@Override
		public void action() {
			// Do nothing, only wait for equation to be solve and then prepare
			Equation result = (Equation) getDataStore().get(RESULT);
			if (result != null) {
				getDataStore().put(RESULT, null);
				prepareDataStore(result);
				isFinish = true;

				// when finish we go again on df
				// create the agent description of itself
				DFAgentDescription dfd = new DFAgentDescription();
				dfd.setName(myAgent.getAID());
				dfd.addOntologies(EquationProducer.EQUATION_ONTOLOGIE);
				// register the description with the DF
				try {
					DFService.register(myAgent, dfd);
				} catch (FIPAException e) {
					e.printStackTrace();
				}
			}

		}

		private void prepareDataStore(Equation result) {
			DataStore ds = getDataStore();
			AchieveREResponder fsm = (AchieveREResponder) getParent();
			ACLMessage request = (ACLMessage) ds.get(fsm.REQUEST_KEY);
			ACLMessage response = (ACLMessage) ds.get(fsm.RESPONSE_KEY);
			ACLMessage resNotification = null;
			try {
				resNotification = prepareResultNotification(request, response,
						result);
			} catch (FailureException fe) {
				resNotification = fe.getACLMessage();
			}
			ds.put(fsm.RESULT_NOTIFICATION_KEY, resNotification);
		}

		// same as if it has been redefine in Equation solver behaviours
		protected ACLMessage prepareResultNotification(ACLMessage request,
				ACLMessage response, Equation result) throws FailureException {

			ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
			msg.addReceiver(request.getSender());
			try {
				msg.setContentObject(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return msg;
		}

		@Override
		public boolean done() {
			return isFinish;
		}

	}

}
